#!/bin/bash

# Input parameters
vm_type=$1
ohos_sdk_native_dir=$2
ENABLE_ASAN=$3

JSVM_BUILD_TARGET_DIRECTORY="jsvm_build"
QJS_BUILD_TARGET_DIRECTORY="qjs_build"
JSC_BUILD_TARGET_DIRECTORY="jsc_build"

# Check if vm_type is provided
if [ -z "$vm_type" ]; then
  echo "ERROR: vm_type is required (qjs, jsvm or jsc)."
  exit 1
fi

# Validate vm_type input
if [ "$vm_type" != "qjs" ] && [ "$vm_type" != "jsvm" ] && [ "$vm_type" != "jsc" ]; then
  echo "ERROR: Invalid vm_type. It should be 'qjs', 'jsvm' or 'jsc'."
  exit 1
fi



# Function to handle the ASAN build
enable_asan() {
  echo "ASAN will be enabled."
  cmake -DCMAKE_BUILD_TYPE=Debug -DVM_TYPE=QJS -DENABLE_ASAN=ON ../
}

# Build process based on vm_type
if [ "$vm_type" == "qjs" ]; then
  # Create build directory if it doesn't exist
  mkdir -p "$QJS_BUILD_TARGET_DIRECTORY"
  cd "$QJS_BUILD_TARGET_DIRECTORY" || { echo "ERROR: Failed to enter the build directory."; exit 1; }
  if [ "$ENABLE_ASAN" == "asan" ]; then
    enable_asan
  else
    cmake -DCMAKE_BUILD_TYPE=Release -DVM_TYPE=QJS ../
  fi
  cmake --build . -v

elif [ "$vm_type" == "jsvm" ]; then
  if [ -z "$ohos_sdk_native_dir" ]; then
    echo "ERROR: ohos_sdk_native_dir is required for jsvm build."
    exit 1
  fi

  # JSVM build with OHOS SDK
  $ohos_sdk_native_dir/build-tools/cmake/bin/cmake \
    -DCMAKE_BUILD_TYPE=Debug \
    -DCMAKE_TOOLCHAIN_FILE=$ohos_sdk_native_dir/build/cmake/ohos.toolchain.cmake \
    -DCMAKE_MAKE_PROGRAM=$ohos_sdk_native_dir/build-tools/cmake/bin/ninja \
    -DCMAKE_SYSTEM_NAME=OHOS \
    -DOHOS_ARCH=arm64-v8a \
    -DVM_TYPE=JSVM \
    -GNinja \
    -B$JSVM_BUILD_TARGET_DIRECTORY

  $ohos_sdk_native_dir/build-tools/cmake/bin/ninja -C $JSVM_BUILD_TARGET_DIRECTORY

elif [ "$vm_type" == "jsc" ]; then
  if [ "$(uname -s)" == "Linux" ]; then
    echo "Building JSC on Linux"
    third_party/WebKit/Tools/Scripts/build-webkit --jsc-only --release ../
  else
    echo "ERROR: unsupported yet"
    exit 1
  fi

  mkdir -p "$JSC_BUILD_TARGET_DIRECTORY"
  cd "$JSC_BUILD_TARGET_DIRECTORY" || { echo "ERROR: Failed to enter the build directory."; exit 1; }

  if [ "$ENABLE_ASAN" == "asan" ]; then
    enable_asan
  else
    cmake -DCMAKE_BUILD_TYPE=Release -DVM_TYPE=JSC ../
  fi
  cmake --build .

fi
